import json

import views

headers = {
    'html': ('Content-Type', 'text/html;charset=utf-8'),
    'json': ('Content-Type', 'application/json;charset=utf-8'),
    'css': ('Content-Type', 'text/css'),
    'jpg': ('Content-Type', 'application/x-jpg'),
    'png': ('Content-Type', 'image/png'),
    'js':('Content-Type','application/javascript')
}


# 第二版
def application(env, start_response):
    # 从服务器获取到用户的请求字符串
    file_name = env['PATH_INFO']
    URL_MAP_DICT = dict()
    # 手工为字典加入映射数据
    URL_MAP_DICT['/'] = views.handler_index
    URL_MAP_DICT['/ccs/bootstrap/css/bootstrap.css'] = views.handler_css
    URL_MAP_DICT['/cache'] = views.mysql_or_cache
    URL_MAP_DICT['/api/server'] = views.mysql_api
    URL_MAP_DICT['/api/v1/host'] = views.mysql_api_v1_host
    URL_MAP_DICT['/server_list'] = views.server_list
    URL_MAP_DICT['/server/js/Popup_window.js'] = views.handler_js

    try:
        # 如果在字典中存在着映射，则指向相应的函数并返回结果
        if 'ccs' in file_name: 
            start_response('200 OK', [headers.get('css')])
        elif 'api' in file_name:
            start_response('200 ok', [headers.get('json')])
        elif 'js' in file_name:
            start_response('200 ok', [headers.get('js')])
        else:
            start_response('200 OK', [headers.get('html')])
        return URL_MAP_DICT[file_name]()
    except Exception as ret:
        # 如果字典中不存在映射， 则返回404
        start_response('404 error', [headers.get('html')])
        return [b"404" +bytes(ret, encoding='utf-8')] 
       

# 第一版
""" def application(env, start_response):
    start_response('200 OK', [headers.get('html')])
    if env['PATH_INFO'] == '/':
        start_response('200 OK', [headers.get('html')])
        return [views.handler_index()]
    elif env['PATH_INFO'] == '/bootstrap/css/bootstrap.css':
        start_response('200 OK', [headers.get('css')])
        return [views.handler_css()]
    elif env["PATH_INFO"] == '/server_list':
        start_response('200 OK', [headers.get('html')])
        return [views.server_list()]
    elif env["PATH_INFO"] == "/cache":
        start_response('200 ok', [headers.get('html')])
        return [views.mysql_or_cache()]
    elif env["PATH_INFO"] == "/api/server":
        start_response('200 ok', [headers.get('json')])
        return [views.mysql_api()]
    else:
        start_response('404 error', [headers.get('html')])
        return [b"404"] 
 """